package com.saleSystem.filter;

/**
 * Created by guanwei on 2017/8/1.
 */
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.saleSystem.pojo.User;

public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession();
        // 获得用户请求的URI
        String path = servletRequest.getRequestURI();

        User user  = (User) session.getAttribute("user");

        boolean flag = false ;
        if(path.contains("ccount") || path.contains("public") || path.contains("edit")){
            flag = true;
        }
        // 登陆页面无需过滤
        if(!flag) {
            System.out.println("this path doesn't need filter");
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 判断如果没有取到用户信息,就跳转到登陆页面
        if (user == null) {
            // 跳转到登陆页面
            System.out.println("NOT LOGIN !");
            servletResponse.sendRedirect("/login");
        } else {
            // 已经登陆,继续此次请求
            chain.doFilter(request, response);
        }
    }

    public void destroy() {
        // TODO Auto-generated method stub
    }
}